//
//  EFADeviceModel.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/26.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFADeviceModel.h"
#import "NSData+XDGZip.h"
#import "NSDate+XDTimerFormatter.h"
#import "UIColor+XDHex.h"
#import "NSString+XDNumber.h"

static NSInteger const kDeviceSubIdLength = 6;

@implementation EFADevPjtUserInfo
@end

@implementation EFADeviceListItem
- (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; }
- (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; }
+ (NSDictionary<NSString *,id> *)modelContainerPropertyGenericClass {
    return @{@"efairydevice_imgurl_list" : [NSString class],
             @"efairyproject_user_info_list" : [EFADevPjtUserInfo class],
             @"efairydevice_user_info_list" : [EFADevPjtUserInfo class]};
}

// 这里来完成自动把UUID分割成两部分subUUID
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
    _efairydevice_main_uuid = [self ccid];
    _efairydevice_sub_uuid = [self uuid_address];
    return YES;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        _efairydevice_belong_system = 10;             ///< 电气火灾监控系统
        _efairydevice_device_type_id = 8;             ///< 初始化为智慧安全用电监控探测器(DDH5268Z)
        NSString *name = [[EFADeviceProtocolModel sharedInstance] deviceTypeDescribeWithType:8];
        _efairydevice_device_type_name = [name copy]; ///< 初始化设备类型
        _efairydevice_sub_uuid = @"1-1-1";            ///< 初始化设备从编码
        _efairydevice_imgurl_list = [NSMutableArray array]; ///< 初始化设备竣工图数组
    }
    return self;
}
- (NSString *)ccid {
    NSRange range = NSMakeRange(0, self.efairydevice_uuid.length - kDeviceSubIdLength);
    NSString *ccidStr = [self.efairydevice_uuid substringWithRange:[self.efairydevice_uuid rangeOfComposedCharacterSequencesForRange:range]];
    return self.efairydevice_uuid ? ccidStr : @"";
}
- (NSString *)uuid_address {
    NSRange range = NSMakeRange(self.efairydevice_uuid.length - kDeviceSubIdLength, kDeviceSubIdLength);
    NSString *idStr = [self.efairydevice_uuid substringWithRange:[self.efairydevice_uuid rangeOfComposedCharacterSequencesForRange:range]];
    if (idStr.length == kDeviceSubIdLength) {
        NSString *zhujiIDStr = [idStr substringWithRange:NSMakeRange(0, 2)];
        NSString *huiluIDStr = [idStr substringWithRange:NSMakeRange(2, 2)];
        NSString *addreIDStr = [idStr substringWithRange:NSMakeRange(4, 2)];
        idStr = [NSString stringWithFormat:@"%ld-%ld-%ld", (unsigned long)[zhujiIDStr xd_hexStrToInteger], (unsigned long)[huiluIDStr xd_hexStrToInteger], (unsigned long)[addreIDStr xd_hexStrToInteger]];
    }
    return self.efairydevice_uuid ? idStr : @"";
}
- (NSString *)map_state_str {
    NSString *threeStr = [[EFADeviceProtocolModel sharedInstance] threeStateDescribeWithSt:self.efairydevice_alarm_id];
    return [NSString stringWithFormat:@"%@(%@)", threeStr, self.efairydevice_is_online ? @"在线" : @"离线"];
}
- (NSString *)mapImgName {
    return [[EFADeviceProtocolModel sharedInstance] threeStateMapImgNameWithSt:self.efairydevice_alarm_id];
}
- (NSString *)listImgName {
    return [[EFADeviceProtocolModel sharedInstance] threeStateListImgNameWithSt:self.efairydevice_alarm_id];
}
- (NSString *)map_state_color {
    return [[EFADeviceProtocolModel sharedInstance] threeStateColorWithSt:self.efairydevice_alarm_id];
}
- (NSString *)three_state_str {
    return [[EFADeviceProtocolModel sharedInstance] threeStateDescribeWithSt:self.efairydevice_alarm_id];
}
- (NSAttributedString *)three_state_attStr {
    NSString *str = [self three_state_str];
    NSString *color = [self map_state_color];
    NSDictionary *dic = @{NSForegroundColorAttributeName : [UIColor xd_colorWithHexString:color]};
    return [[NSAttributedString alloc] initWithString:str attributes:dic];
}
- (void)refreshDeviceTypeName {
    self.efairydevice_device_type_name = [[EFADeviceProtocolModel sharedInstance] deviceTypeDescribeWithType:self.efairydevice_device_type_id];
    
    BOOL need = [[EFADeviceProtocolModel sharedInstance] deviceTypeNeedSubUUIDWithType:self.efairydevice_device_type_id];
    if (!need) {
        self.efairydevice_sub_uuid = @"1-1-1";
    }
}
- (void)composeToUUID {
    NSArray *subIDArray = [self.efairydevice_sub_uuid componentsSeparatedByString:@"-"];
    NSMutableString *mStr = [NSMutableString string];
    for (NSString *subStr in subIDArray) {
        [mStr appendFormat:@"%02lx", (long)[subStr integerValue]];
    }
    self.efairydevice_uuid = [NSString stringWithFormat:@"%@%@", self.efairydevice_main_uuid, mStr];
}
- (void)deComposeUUID {
    self.efairydevice_main_uuid = [self ccid];
    self.efairydevice_sub_uuid = [self uuid_address];
}
@end

@implementation EFADeviceModel
- (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; }
- (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; }

+ (NSDictionary<NSString *,id> *)modelCustomPropertyMapper {
    return @{@"total_rows": @[@"total_rows", @"efairyproject_total_devices"]};
}
+ (NSDictionary<NSString *,id> *)modelContainerPropertyGenericClass {
    return @{@"device_list" : [EFADeviceListItem class]};
}
- (instancetype)init {
    self = [super init];
    if (self) {
        _total_rows = 0;
        _device_list = [NSMutableArray array];
    }
    return self;
}
- (instancetype)initWithListArray:(NSArray<EFADeviceListItem *> *)array {
    NSAssert(array, @"array conn't be nil");
    self = [super init];
    if (self) {
        _total_rows = array.count;
        _device_list = [NSMutableArray arrayWithArray:array];
    }
    return self;
}
- (BOOL)isWholeSel {
    if (!self.device_list.count) {
        return NO;
    }
    
    for (EFADeviceListItem *item in self.device_list) {
        if (!item.efairydevice_user_ownned) {
            return NO;
        }
    }
    return YES;
}
- (BOOL)totalLoad {
    return (self.device_list.count >= self.total_rows);
}
- (BOOL)totalZero {
    return self.device_list.count == 0;
}
- (NSArray<EFADeviceListItem *> *)ownnedDeviceArray {
    NSMutableArray *mArray = [NSMutableArray array];
    for (EFADeviceListItem *item in self.device_list) {
        if (item.efairydevice_user_ownned) {
            [mArray addObject:item];
        }
    }
    return mArray;
}
- (NSArray<NSNumber *> *)idListArray {
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:self.device_list.count];
    for (EFADeviceListItem *item in self.device_list) {
        [mArray addObject:@(item.efairydevice_id)];
    }
    return mArray;
}
- (NSArray<EFADeviceListItem *> *)normalDeviceArray {
    NSMutableArray *mArray = [NSMutableArray array];
    for (EFADeviceListItem *item in self.device_list) {
        if ([item.three_state_str isEqualToString:@"正常"]) {
            [mArray addObject:item];
        }
    }
    return mArray;
}
- (NSArray<EFADeviceListItem *> *)faultDeviceArray {
    NSMutableArray *mArray = [NSMutableArray array];
    for (EFADeviceListItem *item in self.device_list) {
        if ([item.three_state_str isEqualToString:@"故障"]) {
            [mArray addObject:item];
        }
    }
    return mArray;
}
- (NSArray<EFADeviceListItem *> *)alarmDeviceArray {
    NSMutableArray *mArray = [NSMutableArray array];
    for (EFADeviceListItem *item in self.device_list) {
        if ([item.three_state_str isEqualToString:@"报警"]) {
            [mArray addObject:item];
        }
    }
    return mArray;
}
- (void)addMoreWithData:(EFADeviceModel *)temp {
    self.total_rows = temp.total_rows;
    [self.device_list addObjectsFromArray:temp.device_list];
}
- (void)wholeDeviceSelectOrNot:(BOOL)sel {
    [self.device_list enumerateObjectsUsingBlock:^(EFADeviceListItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.efairydevice_user_ownned = sel;
    }];
}
@end


@implementation EFADevPubItem
// 如果实现了该方法，则处理过程中会忽略该列表内的所有属性
+ (NSArray *)modelPropertyBlacklist {
    return @[@"img", @"originalData"];
}
- (instancetype)initWithImage:(UIImage *)img originalData:(NSData *)data imgUrl:(NSString *)url canEdit:(BOOL)canEdit {
    self = [super init];
    if (self) {
        _img = img;
        _originalData = data;
        _image_url = [url copy];
        _canEdit = canEdit;
    }
    return self;
}
@end
@implementation EFADevPubModel
- (instancetype)init {
    self = [super init];
    if (self) {
        _image_list = [NSMutableArray array];
        _imgMaxCnt = 5;
    }
    return self;
}
- (instancetype)initWithImgUrlArray:(NSArray<NSString *> *)urlArray canEdit:(BOOL)canEdit {
    self = [super init];
    if (self) {
        _imgMaxCnt = canEdit ? 5 : urlArray.count;
        _image_list = [NSMutableArray array];
        NSInteger i = 0;
        for (NSString *urlStr in urlArray) {
            EFADevPubItem *item = [[EFADevPubItem alloc] initWithImage:nil originalData:nil imgUrl:urlStr canEdit:canEdit];
            [_image_list addObject:item];
            if (++i >= _imgMaxCnt) {
                break;
            }
        }
    }
    return self;
}
- (BOOL)isEmpty {
    return !(self.image_list.count);
}
- (BOOL)isImgUpload {
    for (EFADevPubItem *item in self.image_list) {
        if (item.image_url.length == 0) {
            return NO;
        }
    }
    return YES;
}
- (NSArray<UIImage *> *)needUploadImgArray {
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:self.image_list.count];
    [self.image_list enumerateObjectsUsingBlock:^(EFADevPubItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.img && obj.image_url.length == 0) {
            [mArray addObject:obj.img];
        }
    }];
    return mArray;
}
- (NSArray<UIImage *> *)imgArray {
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:self.image_list.count];
    [self.image_list enumerateObjectsUsingBlock:^(EFADevPubItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [mArray addObject:obj.img];
    }];
    return mArray;
}
- (NSArray<NSString *> *)urlArray {
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:self.image_list.count];
    [self.image_list enumerateObjectsUsingBlock:^(EFADevPubItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [mArray addObject:obj.image_url];
    }];
    return mArray;
}
- (void)addPublishItemsWithImgArray:(NSArray<UIImage *> *)imgArray originalDataArray:(NSArray<NSData *> *)dataArray {
    [imgArray enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSData *originalData = nil;
        if (idx < dataArray.count) {
            originalData = dataArray[idx];
        }
        EFADevPubItem *item = [[EFADevPubItem alloc] initWithImage:obj originalData:originalData imgUrl:nil canEdit:YES];
        [self.image_list addObject:item];
    }];
}
- (void)removePublishItemAtIndex:(NSInteger)index {
    if (index < self.image_list.count) {
        [self.image_list removeObjectAtIndex:index];
    }
}
- (void)updateImgUrlWithArray:(NSArray<NSString *> *)array {
    if (array.count != self.needUploadImgArray.count) {
        return;
    }
    
    NSInteger j = 0;
    for (NSInteger i = 0; i < self.image_list.count; ++i) {
        EFADevPubItem *item = self.image_list[i];
        if (item.img && (item.image_url.length == 0) && (j < array.count)) {
            item.image_url = array[j];
            j++;
        }
    }
}
@end



@implementation EFADevPtCidItem
- (instancetype)init {
    self = [super init];
    if (self) {
        _cidArray = [NSMutableArray array];
    }
    return self;
}
- (instancetype)initWithPt:(NSInteger)pt cid:(NSInteger)cid thv:(NSInteger)thv{
    self = [super init];
    if (self) {
        _pt = pt;
        _cidArray = [@[@(cid)] mutableCopy];
        _thv = thv;
    }
    return self;
}
- (NSString *)cidTitleWithCid:(NSNumber *)cid {
    if ([cid integerValue] == 9) {
        return @"烟感探测";
    }
    if ([cid integerValue] == 10) {
        return @"气体探测";
    }
    NSDictionary *dic = [[EFADeviceProtocolModel sharedInstance] protocolInfoWithPt:self.pt];
    return dic[EFADeviceProtocolPtTitle];
}
- (NSInteger)cidDisplayWithCid:(NSNumber *)cid {
    NSInteger cidInt = [cid integerValue];
    if (cidInt == 9 || cidInt == 10) {
        return cidInt - 8;
    }
    return cidInt;
}
@end

@implementation ValueRange
- (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; }
- (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; }
@end

@implementation EFADevRealTimeDataItem
- (NSInteger)cidDisplay {
    if (self.cid == 9 || self.cid == 10) {
        return self.cid - 8;
    }
    return self.cid;
}
- (NSString *)cidTitle {
    if (self.cid == 9) {
        return @"烟感探测";
    }
    if (self.cid == 10) {
        return @"气体探测";
    }
    NSDictionary *dic = [[EFADeviceProtocolModel sharedInstance] protocolInfoWithPt:self.pt];
    return dic[EFADeviceProtocolPtTitle];
}

+ (NSDictionary<NSString *,id> *)modelContainerPropertyGenericClass {
    return @{@"value_range" : [ValueRange class]};
}

- (NSString *)rtvValue {
    BOOL isSwitch = [[EFADeviceProtocolModel sharedInstance] isSwitchPt:self.pt];
    if (isSwitch) {
        NSString *rtvStr = [[EFADeviceProtocolModel sharedInstance] rtvSwitchDescribeWithRtv:self.rtv pt:self.pt];
        NSString *thvStr = [[EFADeviceProtocolModel sharedInstance] thvSwitchDescribeWithThv:self.thv pt:self.pt];
        return [NSString stringWithFormat:@"%@/%@", rtvStr, thvStr];
    } else {
        NSDictionary *dic = [[EFADeviceProtocolModel sharedInstance] protocolInfoWithPt:self.pt];
        NSString* format = [NSString stringWithFormat:@"%%.%ldf%%@/%%.%ldf%%@", (long)[dic[EFADeviceProtocolPtDecNum] integerValue], (long)[dic[EFADeviceProtocolPtDecNum] integerValue]];
        return [NSString stringWithFormat:format, self.rtv * [dic[EFADeviceProtocolPtMultiple] floatValue], dic[EFADeviceProtocolPtUnit], self.thv * [dic[EFADeviceProtocolPtMultiple] floatValue], dic[EFADeviceProtocolPtUnit]];
    }
}
- (NSString *)thvValue {
    BOOL isSwitch = [[EFADeviceProtocolModel sharedInstance] isSwitchPt:self.pt];
    if (isSwitch) {
        NSString *thvStr = [[EFADeviceProtocolModel sharedInstance] thvSwitchDescribeWithThv:self.thv pt:self.pt];
        return [NSString stringWithFormat:@"%@", thvStr];
    } else {
        NSDictionary *dic = [[EFADeviceProtocolModel sharedInstance] protocolInfoWithPt:self.pt];
        NSString* format = [NSString stringWithFormat:@"%%.%ldf%%@", (long)[dic[EFADeviceProtocolPtDecNum] integerValue]];
        return [NSString stringWithFormat:format, self.thv * [dic[EFADeviceProtocolPtMultiple] floatValue], dic[EFADeviceProtocolPtUnit]];
    }
}
- (NSInteger)thvStart {
    NSDictionary *dic = [[EFADeviceProtocolModel sharedInstance] protocolInfoWithPt:self.pt];
    float multiple = [dic[EFADeviceProtocolPtMultiple] floatValue];
//    return [dic[EFADeviceProtocolPtThvStart] integerValue] * multiple;    ///< 之前是根据文档写死的，现在根据服务器返回
    return self.min * multiple;
}
- (NSInteger)thvEnd {
    NSDictionary *dic = [[EFADeviceProtocolModel sharedInstance] protocolInfoWithPt:self.pt];
    float multiple = [dic[EFADeviceProtocolPtMultiple] floatValue];
//    return [dic[EFADeviceProtocolPtThvEnd] integerValue] * multiple;
    return self.max * multiple;
}
- (NSString *)ptUnit {
    NSDictionary *dic = [[EFADeviceProtocolModel sharedInstance] protocolInfoWithPt:self.pt];
    return dic[EFADeviceProtocolPtUnit];
}
- (void)configThv:(NSInteger)thv {
    NSDictionary *dic = [[EFADeviceProtocolModel sharedInstance] protocolInfoWithPt:self.pt];
    float multiple = [dic[EFADeviceProtocolPtMultiple] floatValue];
    self.thv = thv / multiple;
}
@end
@implementation EFADevRealTimeData
+ (NSDictionary<NSString *,id> *)modelContainerPropertyGenericClass {
    return @{@"data" : [EFADevRealTimeDataItem class]};
}
- (NSMutableArray<EFADevRealTimeDataItem *> *)filterData {
    if (!_filterData) {
        NSMutableArray *temp = [NSMutableArray arrayWithCapacity:self.data.count];
        for (EFADevRealTimeDataItem *item in self.data) {
            if (item.cid != 0) {
                [temp addObject:item];
            }
        }
        _filterData = temp;
    }
    return _filterData;
}
- (NSString *)tsStr {
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:self.ts];
    return [date xd_yyyy_MM_ddHHmmss];
}
- (NSInteger)heartRate {
    for (EFADevRealTimeDataItem *item in self.data) {
        if (item.cid == 0) {    ///< 0通道的st代表心跳间隔，rtv代表音响模式
            return item.st;
        }
    }
    return 0;
}
- (BOOL)muteMode {
    for (EFADevRealTimeDataItem *item in self.data) {
        if (item.cid == 0) {
            return (item.pt & 0xFF);
        }
    }
    return YES;
}
@end
@implementation EFADeviceInfoModel
+ (NSDictionary<NSString *,id> *)modelContainerPropertyGenericClass {
    return @{@"data_stream_list" : [NSString class]};
}
- (void)unzipStreamList {
    if(self.unzipStream == nil){
        self.unzipStream = [[NSMutableArray alloc]init];
    }
    [self.unzipStream removeAllObjects];
    if(self.data_stream_list.count && self.data_stream_list.count > 0 ){
        for(int i = 0; i< self.data_stream_list.count; i++){
              NSData *data = nil;
              data = [[NSData alloc] initWithBase64EncodedString:self.data_stream_list[i] options:NSDataBase64DecodingIgnoreUnknownCharacters];
            if (!data.length) {
                NSLog(@"转换Base64到NSData出错");
                continue;
            }
            
            // 解压data
            NSData *unzipData = [data xd_gzipInflate];
            if (!unzipData.length) {
                NSLog(@"解压NSData出错");
                return;
            }
            NSArray<NSString *> *temp = [NSJSONSerialization JSONObjectWithData:unzipData options:NSJSONReadingMutableContainers error:nil];
            if (!temp.count) {
                NSLog(@"NSData转换到NSArray出错");
                return;
            }
            NSLog(@"解压之后，转换为json，数组的大小 = %ld", (unsigned long)temp.count);
//            NSMutableArray<EFADevRealTimeData *> *mArray = [NSMutableArray arrayWithCapacity:temp.count];
            // 倒序遍历
            [temp enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                EFADevRealTimeData *item = [EFADevRealTimeData yy_modelWithJSON:obj];
                if (item) [self.unzipStream  addObject:item];
            }];
//            [self.unzipStream addObjectsFromArray:mArray];
        }
    }
    NSLog(@"倒序整理之后数据的大小 = %ld", (unsigned long)self.unzipStream.count);
   
}
- (NSArray<EFADevPtCidItem *> *)streamPtCidArray {
    if (!_streamPtCidArray) {
        _streamPtCidArray = [self sortStreamPtCidArray];
    }
    return _streamPtCidArray;
}
- (NSArray<EFADevPtCidItem *> *)sortStreamPtCidArray {
    NSArray *maxArray = @[];
    for (EFADevRealTimeData *oneTime in self.unzipStream) {
        NSMutableArray<EFADevPtCidItem *> *temp = [NSMutableArray array];
        for (EFADevRealTimeDataItem *oneCid in oneTime.data) {
            if (oneCid.cid == 0) {  // 不处理0通道
                continue;
            }
            BOOL isFind = NO;
            for (EFADevPtCidItem *ptItem in temp) {
                if (ptItem.pt == oneCid.pt) {
                    if (![ptItem.cidArray containsObject:@(oneCid.cid)]) {
                        [ptItem.cidArray addObject:@(oneCid.cid)];
                    }
                    isFind = YES;
                    break;
                }
            }
            if (!isFind) {
                EFADevPtCidItem *ptItemNew = [[EFADevPtCidItem alloc] initWithPt:oneCid.pt cid:oneCid.cid thv:oneCid.thv];
                [temp addObject:ptItemNew];
            }
        }
        maxArray = (maxArray.count > temp.count) ? maxArray : temp;
    }
    return maxArray;
}
- (NSArray<NSString *> *)timestampArray {
    if (!_timestampArray) {
        _timestampArray = [self sortTimestampArray];
    }
    return _timestampArray;
}
- (NSArray<NSString *> *)sortTimestampArray {
    NSMutableArray *mArray = [[NSMutableArray alloc]init];
//    for (EFADevRealTimeData *oneTime in self.unzipStream) {
//        NSDate *date = [NSDate dateWithTimeIntervalSince1970:oneTime.ts];
//        [mArray addObject:[date xd_MM_ddHHmm]];
//    }
    int todaySize = 1;
    if(self.unzipStream.count >= 1000){
        todaySize = (int)self.unzipStream.count/500;//一共显示500到999条数据 当小1000条数据的时候有多少条显示多少条
    }
    [self.unzipStream enumerateObjectsUsingBlock:^(EFADevRealTimeData * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx % todaySize == 0) {
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:obj.ts];
            [mArray addObject:[date xd_MM_ddHHmm]];
        }
    }];
    return mArray;
}
- (NSArray<NSNumber *> *)rtvArrayWithCid:(NSInteger)cid pt:(NSInteger)pt {
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:self.unzipStream.count];
    NSDictionary *dic = [[EFADeviceProtocolModel sharedInstance] protocolInfoWithPt:pt];
//    float multiple = [dic[EFADeviceProtocolPtMultiple] floatValue];
    double multiple = [dic[EFADeviceProtocolPtMultiple] doubleValue];
//    for (EFADevRealTimeData *oneTime in self.unzipStream) {
//        BOOL isFind = NO;
//        for (EFADevRealTimeDataItem *oneCid in oneTime.data) {
//            if (oneCid.cid == cid && oneCid.pt == pt) {
//                [mArray addObject:@(oneCid.rtv * multiple)];
//                isFind = YES;
//                break;
//            }
//        }
//        if (!isFind) {
//            [mArray addObject:@(0)];        //!< 某一个通道没有值就用0代替
//        }
//    }
    // 暂时优化为5个点取1个点
    NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
    int todaySize = 1;
    if(self.unzipStream.count >= 1000){
        todaySize = (int)self.unzipStream.count/500;//一共显示500到999条数据 当小1000条数据的时候有多少条显示多少条
    }
    [self.unzipStream enumerateObjectsUsingBlock:^(EFADevRealTimeData * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx % todaySize == 0) {
            BOOL isFind = NO;
            for (EFADevRealTimeDataItem *oneCid in obj.data) {
                if (oneCid.cid == cid && oneCid.pt == pt) {
                    NSString *str = [NSString stringWithFormat:@"%@", @(oneCid.rtv * multiple)];
                    NSNumber *num = [format numberFromString:str];
                    [mArray addObject:(num ? num : @(0))];  ///< 防止出现num = nil的情况
                    // 这里的老方法会出现很多小数点
//                    [mArray addObject:@(oneCid.rtv * multiple)];
                    isFind = YES;
                    break;
                }
            }
            if (!isFind) {
                [mArray addObject:@(0)];        //!< 某一个通道没有值就用0代替
            }
        }
    }];
    NSLog(@"数据大小： %ld",mArray.count);
    return mArray;
}
@end


#pragma mark - 传输协议
NSString *const EFADeviceProtocolPtType = @"type";            //!< 参量类型的Key
NSString *const EFADeviceProtocolPtTitle = @"title";          //!< 参量类型的描述
NSString *const EFADeviceProtocolPtUnit = @"unit";            //!< 参量类型的单位
NSString *const EFADeviceProtocolPtMultiple = @"multiple";    //!< 参量类型的倍数
NSString *const EFADeviceProtocolPtDecNum = @"decNum";        //!< 小数点的位数
NSString *const EFADeviceProtocolPtThvStart = @"thvStart";    //!< 阈值起始值
NSString *const EFADeviceProtocolPtThvEnd = @"thvEnd";        //!< 阈值终止值
@implementation EFADeviceProtocolModel
- (NSArray *)ptArray {
    if (!_ptArray) {
        _ptArray = @[@{@"type"     : @(0),
                       @"title"    : @"预留",
                       @"unit"     : @"",
                       @"multiple" : @(1),
                       @"decNum"   : @(0),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(1),
                       @"title"    : @"高度",
                       @"unit"     : @"m",
                       @"multiple" : @(0.01),
                       @"decNum"   : @(2),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(2),
                       @"title"    : @"温度",
                       @"unit"     : @"°C",
                       @"multiple" : @(0.1),
                       @"decNum"   : @(1),
                       @"thvStart" : @(450),
                       @"thvEnd"   : @(1400)},
                     
                     @{@"type"     : @(3),
                       @"title"    : @"压力",
                       @"unit"     : @"MPa",
                       @"multiple" : @(0.1),
                       @"decNum"   : @(1),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(4),
                       @"title"    : @"压力",
                       @"unit"     : @"kPa",
                       @"multiple" : @(0.1),
                       @"decNum"   : @(1),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(5),
                       @"title"    : @"气体浓度",
                       @"unit"     : @"%LEL",
                       @"multiple" : @(0.1),
                       @"decNum"   : @(1),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(6),
                       @"title"    : @"气体浓度",
                       @"unit"     : @"%VOL",
                       @"multiple" : @(0.1),
                       @"decNum"   : @(1),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(7),
                       @"title"    : @"气体浓度",
                       @"unit"     : @"10^-6体积分数",
                       @"multiple" : @(1),
                       @"decNum"   : @(0),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(8),
                       @"title"    : @"气体浓度",
                       @"unit"     : @"mg/m3",
                       @"multiple" : @(1),
                       @"decNum"   : @(0),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(9),
                       @"title"    : @"时间",
                       @"unit"     : @"s",
                       @"multiple" : @(1),
                       @"decNum"   : @(0),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(10),
                       @"title"    : @"电压",
                       @"unit"     : @"V",
                       @"multiple" : @(0.1),
                       @"decNum"   : @(1),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(11),
                       @"title"    : @"电流",
                       @"unit"     : @"A",
                       @"multiple" : @(0.1),
                       @"decNum"   : @(1),
                       @"thvStart" : @(100),
                       @"thvEnd"   : @(9999)},
                     
                     @{@"type"     : @(12),
                       @"title"    : @"流量",
                       @"unit"     : @"L/s",
                       @"multiple" : @(0.1),
                       @"decNum"   : @(1),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(13),
                       @"title"    : @"风量",
                       @"unit"     : @"m3/min",
                       @"multiple" : @(0.1),
                       @"decNum"   : @(1),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(14),
                       @"title"    : @"风速",
                       @"unit"     : @"m/s",
                       @"multiple" : @(0.1),
                       @"decNum"   : @(1),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(15),
                       @"title"    : @"漏电",
                       @"unit"     : @"mA",
                       @"multiple" : @(1),
                       @"decNum"   : @(0),
                       @"thvStart" : @(200),
                       @"thvEnd"   : @(999)},
                     
                     @{@"type"     : @(16),
                       @"title"    : @"烟参量",
                       @"unit"     : @"自定义",
                       @"multiple" : @(1),
                       @"decNum"   : @(0),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(0)},
                     
                     @{@"type"     : @(128),
                       @"title"    : @"输入检测",
                       @"unit"     : @"",
                       @"multiple" : @(1),
                       @"decNum"   : @(0),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(2)},
                     
                     @{@"type"     : @(129),
                       @"title"    : @"输出检测",
                       @"unit"     : @"",
                       @"multiple" : @(1),
                       @"decNum"   : @(0),
                       @"thvStart" : @(0),
                       @"thvEnd"   : @(2)}];
    }
    return _ptArray;
}
- (NSArray *)ptSwitchArray {
    if (!_ptSwitchArray) {
        _ptSwitchArray = @[@{@"type" : @(128),
                             @"rtv" : @{@(0) : @"正常", @(1) : @"报警"},
                             @"thv" : @{@(0) : @"不启用", @(1) : @"常开检测", @(2) : @"常闭检测"}},
                           @{@"type" : @(129),
                             @"rtv" : @{@(0) : @"正常", @(1) : @"报警"},
                             @"thv" : @{@(0) : @"不启用", @(1) : @"报警电平输出", @(2) : @"报警脉冲输出"}}];
    }
    return _ptSwitchArray;
}
- (NSDictionary *)stDics {
    if (!_stDics) {
        _stDics = @{@(0) : @"预留",
                    @(1) : @"正常",
                    @(2) : @"火警",
                    @(3) : @"启动",
                    @(4) : @"动作",
                    @(5) : @"监管",
                    @(6) : @"故障",
                    @(7) : @"自检",
                    
                    @(21) : @"通讯故障",
                    @(22) : @"主电故障",
                    @(23) : @"备电故障",
                    @(24) : @"线路故障",
                    
                    @(40) : @"故障恢复",
                    @(41) : @"通讯故障恢复",
                    @(42) : @"主电故障恢复",
                    @(43) : @"备电故障恢复",
                    @(44) : @"线路故障恢复",
                    
                    @(70) : @"停止",
                    @(71) : @"屏蔽",
                    @(72) : @"屏蔽撤销",
                    @(73) : @"开机",
                    @(74) : @"关机",
                    @(75) : @"复位",
                    @(76) : @"手动状态",
                    @(77) : @"自动状态",
                    @(78) : @"确认/消音",
                    
                    @(128) : @"主电欠压故障",
                    @(129) : @"主电欠压恢复",
                    @(130) : @"备电欠压故障",
                    @(131) : @"备电欠压恢复",
                    @(132) : @"温度传感器短路",
                    @(133) : @"温度传感器短路恢复",
                    @(134) : @"温度传感器开路",
                    @(135) : @"温度传感器开路恢复",
                    @(136) : @"电流互感器短路",
                    @(137) : @"电流互感器短路恢复",
                    @(138) : @"电流互感器开路",
                    @(139) : @"电流互感器开路恢复",
                    @(140) : @"漏电预警",
                    @(141) : @"温度预警",
                    @(142) : @"过流预警",
                    @(143) : @"漏电报警",
                    @(144) : @"温度报警",
                    @(145) : @"过流报警",
                    @(146) : @"电源短路故障",
                    @(147) : @"电源短路故障恢复",
                    @(148) : @"回路短路",
                    @(149) : @"回路短路恢复",
                    @(150) : @"回路通信故障",
                    @(151) : @"回路通信故障恢复",
                    @(152) : @"输出线故障",
                    @(153) : @"输出线故障恢复",
                    @(154) : @"输入线故障",
                    @(155) : @"输入线故障恢复",
                    @(156) : @"模块电源故障",
                    @(157) : @"模块电源故障恢复",
                    @(158) : @"新设备注册",
                    @(159) : @"打印机故障",
                    @(160) : @"打印机故障恢复",
                    @(161) : @"打印机缺纸",
                    @(162) : @"打印机缺纸恢复",
                    @(163) : @"系统故障",
                    @(164) : @"系统故障恢复",
                    @(165) : @"反馈",
                    @(166) : @"停止反馈",
                    @(167) : @"",
                    @(168) : @""};
    }
    return _stDics;
}
- (NSDictionary *)sortStDics {
    if (!_sortStDics) {
        _sortStDics = @{@(0) : @"离线",
                        @(1) : @"火警",
                        @(2) : @"预警",
                        @(3) : @"故障",
                        @(4) : @"启动",
                        @(5) : @"屏蔽",
                        @(6) : @"正常"};
    }
    return _sortStDics;
}
- (NSArray *)threeStArray {
    if (!_threeStArray) {
        _threeStArray = @[@{@"mapImg" : @"device_map_green",
                            @"listImg" : @"device_list_green",
                            @"color" : @"0x60C256",
                            @"title" : @"正常",
                            @"st" : @[@(5), @(6)]},
                          @{@"mapImg" : @"device_map_yellow",
                            @"listImg" : @"device_list_yellow",
                            @"color" : @"0xFDA03C",
                            @"title" : @"故障",
                            @"st" : @[@(0), @(3)]},
                          @{@"mapImg" : @"device_map_red",
                            @"listImg" : @"device_list_red",
                            @"color" : @"0xFE5F56",
                            @"title" : @"报警",
                            @"st" : @[@(1), @(2), @(4)]}];
    }
    return _threeStArray;
}
- (NSArray *)sysDevTypeArray {
    if (!_sysDevTypeArray) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"PSTSystemDeviceType" ofType:@"plist"];
        _sysDevTypeArray = [NSArray arrayWithContentsOfFile:path];
    }
    return _sysDevTypeArray;
}
- (NSArray<NSNumber *> *)needInputSubUUIDArray {
    if (!_needInputSubUUIDArray) {
        _needInputSubUUIDArray = @[@(1), @(2), @(7), @(9), @(11), @(12), @(13)];
    }
    return _needInputSubUUIDArray;
}
+ (instancetype)sharedInstance {
    static EFADeviceProtocolModel *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
- (NSDictionary *)protocolInfoWithPt:(NSInteger)pt {
    for (NSDictionary *dic in self.ptArray) {
        if ([dic[@"type"] integerValue] == pt) {
            return dic;
        }
    }
    return nil;
}
- (NSString *)stateDescribeWithSt:(NSInteger)st {
    NSString *des = self.stDics[@(st)];
    if (des) {
        return des;
    }
    return [NSString stringWithFormat:@"错误参数(%ld)未定义", (long)st];
}
- (NSString *)sortStateDescribeWithSt:(NSInteger)st {
    NSString *des = self.sortStDics[@(st)];
    if (des) {
        return des;
    }
    return [NSString stringWithFormat:@"错误参数(%ld)未定义", (long)st];
}
- (BOOL)isSwitchPt:(NSInteger)pt {
    for (NSDictionary *dic in self.ptSwitchArray) {
        if ([dic[@"type"] integerValue] == pt) {
            return YES;
        }
    }
    return NO;
}
- (NSString *)rtvSwitchDescribeWithRtv:(NSInteger)rtv pt:(NSInteger)pt {
    for (NSDictionary *dic in self.ptSwitchArray) {
        if ([dic[@"type"] integerValue] == pt) {
            NSDictionary *temp = dic[@"rtv"];
            return temp[@(rtv)];
        }
    }
    return nil;
}
- (NSString *)thvSwitchDescribeWithThv:(NSInteger)thv pt:(NSInteger)pt {
    for (NSDictionary *dic in self.ptSwitchArray) {
        if ([dic[@"type"] integerValue] == pt) {
            NSDictionary *temp = dic[@"thv"];
            return temp[@(thv)];
        }
    }
    return nil;
}
- (NSArray<NSNumber *> *)thvRangeArrayWithPt:(NSInteger)pt {
    for (NSDictionary *dic in self.ptSwitchArray) {
        if ([dic[@"type"] integerValue] == pt) {
            NSDictionary *temp = dic[@"thv"];
            return temp.allKeys;
        }
    }
    return nil;
}
- (NSString *)deviceTypeDescribeWithType:(NSInteger)type {
    for (NSDictionary *dic in self.sysDevTypeArray) {
        for (NSDictionary *devDic in dic[@"device_type_list"]) {
            if ([devDic[@"device_type_id"] integerValue] == type) {
                return devDic[@"device_type_name"];
            }
        }
    }
//    return [NSString stringWithFormat:@"预留(%ld)", (long)type];
    return @"";
}
- (BOOL)deviceTypeNeedSubUUIDWithType:(NSInteger)type {
    for (NSNumber *item in self.needInputSubUUIDArray) {
        if ([item integerValue] == type) {
            return YES;
        }
    }
    return NO;
}
- (NSArray<NSDictionary *> *)deviceTypeArrayWithSystemTypeId:(NSInteger)sysTypeId {
    for (NSDictionary *dic in self.sysDevTypeArray) {
        if ([dic[@"system_type_id"] integerValue] == sysTypeId) {
            return dic[@"device_type_list"];
        }
    }
    return @[];
}
- (NSString *)threeStateDescribeWithSt:(NSInteger)st {
    NSDictionary *dic = [self threeStateDicWithSt:st];
    return dic ? dic[@"title"] : @"未知错误";
}
- (NSString *)threeStateMapImgNameWithSt:(NSInteger)st {
    NSDictionary *dic = [self threeStateDicWithSt:st];
    return dic ? dic[@"mapImg"] : @"device_map_yellow";
}
- (NSString *)threeStateListImgNameWithSt:(NSInteger)st {
    NSDictionary *dic = [self threeStateDicWithSt:st];
    return dic ? dic[@"listImg"] : @"device_list_yellow";
}
- (NSString *)threeStateColorWithSt:(NSInteger)st {
    NSDictionary *dic = [self threeStateDicWithSt:st];
    return dic ? dic[@"color"] : @"0xFDA03C";
}
- (NSDictionary *)threeStateDicWithSt:(NSInteger)st {
    for (NSDictionary *dic in self.threeStArray) {
        NSArray *stArray = dic[@"st"];
        if ([stArray containsObject:@(st)]) {
            return dic;
        }
    }
    return nil;
}
@end
